import { Direction } from "../context";

// 检测碰撞
export function checkCollision(a: Point, b: Point) {
  return a.x === b.x && a.y === b.y;
}

// 是否越界
export function isOutOfBounds(
  left: number,
  top: number,
  stageWidth: number,
  stageHeight: number
) {
  // 检查left和top是否小于0或者大于舞台的宽高
  return left < 0 || left >= stageWidth || top < 0 || top >= stageHeight;
}

// 是否横向移动
export function isHorizontalMove(direction: string) {
  return direction === Direction.right || direction === Direction.left;
}

// 是否纵向移动
export function isVerticalMove(direction: string) {
  return direction === Direction.up || direction === Direction.down;
}

// 是否可以改变方向
export function isDirection(direction: string, eventKey: string) {
  if (
    Object.values(Direction).includes(eventKey as Direction) &&
    direction !== eventKey
  ) {
    if (
      (direction === Direction.right && eventKey !== Direction.left) ||
      (direction === Direction.left && eventKey !== Direction.right) ||
      (direction === Direction.down && eventKey !== Direction.up) ||
      (direction === Direction.up && eventKey !== Direction.down)
    ) {
      return true;
    }
  }
  return false;
}

// 生成随机坐标
export function getRandomPoint(
  width: number,
  height: number,
  stageWidth: number,
  stageHeight: number
) {
  // 计算横向可切割的份数
  const numColumns = Math.floor(stageWidth / width);
  // 计算纵向可切割的份数
  const numRows = Math.floor(stageHeight / height);

  // 随机选择一个横向的格子索引
  const randomColumnIndex = Math.floor(Math.random() * numColumns);
  // 随机选择一个纵向的格子索引
  const randomRowIndex = Math.floor(Math.random() * numRows);

  // 计算随机点的left坐标，使其落在格子的左上角起始点
  const left = randomColumnIndex * height;
  // 计算随机点的top坐标，使其落在格子的左上角起始点
  const top = randomRowIndex * height;

  return {
    x: left,
    y: top,
  };
}
